#include "DoubleLoopList.h"
#include<stdlib.h>
#include<iostream>
using namespace std;
void init(DNode* head)
{
	head->val = 0;
	head->next = head->prev = head;
}

static void inserNode(DNode* prev, DNode* new_node, DNode* next)
{
	next->prev = new_node;
	new_node->next = next;
	new_node->prev = prev;
	prev->next = new_node;
}

static void delElement(DNode* prev, DNode* next)
{
	next->prev = prev;
	prev->next = next;
}

void inserHead(DNode* head, Element_t e)
{
	DNode* new_node = (DNode*)malloc(sizeof(DNode));
	new_node->val = e;
	inserNode(head, new_node, head->next);
	++head->val;
}

void inserTail(DNode* head, Element_t e)
{
	DNode* new_node = (DNode*)malloc(sizeof(DNode));
	new_node->val = e;
	inserNode(head->prev, new_node, head);
	++head->val;
}

void inserPos(DNode* head, int pos, Element_t e)
{
	DNode* p = head->next;
	for (int i = 1; i < pos; i++)
	{
		p = p->next;
	}
	DNode* new_node = (DNode*)malloc(sizeof(DNode));
	new_node->val = e;
	inserNode(p->prev, new_node, p);
	++head->val;
}

void delElment(DNode* head, Element_t e)
{
	DNode* p = head->next;
	while (p != head && p->val != e)
	{
		p = p->next;
	}
	delElement(p->prev, p->next);
	free(p);
}


void showList(const DNode* head)
{
	DNode* p = head->next;
	while (p != head)
	{
		cout << p->val << " ";
		p = p->next;
	}
	cout << endl;
}

void releaseList(DNode* head)
{
	DNode* p = head->next;
	DNode* tmp = p;
	while (p!= head)
	{
		delElement(p->prev, p->next);
		p = p->next;
		free(tmp);
	}
}


